package com.masterclient.app.businessmodule.usermodule.login.contract;

import android.support.annotation.NonNull;

import com.eoner.common.config.Config;
import com.eoner.baselib.presenter.ThrowableConsumer;
import com.masterclient.app.businessmodule.usermodule.api.UserHttpService;
import com.masterclient.app.businessmodule.usermodule.login.beans.CaptchaBean;
import com.eoner.baselibrary.utils.EncryptUtil;
import com.masterclient.app.utils.CaptchaUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;

/**
* Created by TMVPHelper on 2017/07/12
*/
public class ForgetPwdPresenter extends ForgetPwdContract.Presenter{

    @Override
    public void getCaptcha(@NonNull String phoneNum,@NonNull String type,String ne) {
        mView.baseShowCommitLoading("");
        String captchaValidate = "";
        if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES){
            Map<String,String> map = new HashMap<>();
            map.put("failureNum","3");
            map.put("clientTime",System.currentTimeMillis()/1000+"");
            captchaValidate = EncryptUtil.encryptRSA(new Gson().toJson(map),Config.captchaKey);
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile",phoneNum);
            jsonObject.put("type",type);
            jsonObject.put("NECaptchaValidate",ne);
            jsonObject.put("captchaValidate",captchaValidate);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<CaptchaBean> observable = UserHttpService.getInstance().getCaptcha(body);
        Disposable disposable = toSubscribe(observable, new Consumer<CaptchaBean>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull CaptchaBean bean) throws Exception {
                mView.baseHiddenCommitLoading();
                if("0".equals(bean.getCode())){
                    mView.getCaptchaResult("" + true);
                }else {
                    mView.showError(bean.getMsg());
                }
            }
        },new ThrowableConsumer(){
            @Override
            public void accept(@io.reactivex.annotations.NonNull Throwable o) throws Exception {
                super.accept(o);
                mView.baseHiddenCommitLoading();
                mView.showError("获取验证码失败");
            }
        });
        mRxManager.add(disposable);
    }
}